package com.xunfang.demo.servlet3;

import com.xunfang.demo.entity.UserDemo;
import com.xunfang.demo.service.UserService;
import com.xunfang.demo.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "MainServlet", urlPatterns = "/main")
public class MainServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String userName = (String) request.getSession().getAttribute("username");
        if(userName==null){
            //response.sendRedirect(request.getContextPath()+"/index.jsp");
            response.getWriter().write("<h1>请登录后在进行操作，5秒之后，跳转到登录页面！</h1>");
            //refresh: 响应头，表示多少秒之后，跳转到指定的url
            response.setHeader("refresh","5;url="+request.getContextPath()+"/index.jsp");
            return;
        }
        System.out.println("成功登录！！！");
        //问题： 如何把从数据库中查询出来的用户数据，显示到页面上？
        List<UserDemo> list = userService.findUserAll();
        //注意：如果想在main.jsp中显示数据，那么必须要把list放到【域对象】中，传递到main.jsp中。
        request.setAttribute("list",list);
        //请求转发数据到main.jsp
        request.getRequestDispatcher("/main.jsp").forward(request,response);

        /*PrintWriter w = response.getWriter();
        w.write("<h1>用户列表</h1>");
        w.write("<table width=800 border='1'>");
        w.write("<tr>" +
                "<th>编号</th>" +
                "<th>姓名</th>" +
                "<th>生日</th>" +
                "<th>操作</th>" +
                "</tr>");
        for (UserDemo userDemo : list) {
            w.write("<tr>");
            w.write("<td>"+userDemo.getId()+"</td>");
            w.write("<td>"+userDemo.getUserName()+"</td>");
            w.write("<td>"+userDemo.getBirthday()+"</td>");
            ///day25_request/del?xxx=xxx&yyy=yyy&ttt=ttt...
            w.write("<td><a href='/day25_request/del?id="+userDemo.getId()+"'>删除</a></td>");
            w.write("</tr>");
        }
        w.write("</table>");
        w.write("<a href='/day25_request/login.html'>返回登录</a>");*/
    }
}
